using Space2D;
using System.Collections.Generic;
using UnityEngine;

public class CollisionDetectionAABB : CollisionDetectionBase
{
    private List<List<Vector2>> polys = new List<List<Vector2>>();
    private AABBTree tree;
    private List<AABBNode> hitNodes;
    private AABB aabbSelect = new AABB();

    public override bool IsOverlap()
    {
        return false;
    }
    public override void CheckOverlap(List<Shape2D> shapeList, int selectedIndex)
    {
        polys.Clear();
        for (int i = 0; i < shapeList.Count; i++)
        {
            Shape2D shape = shapeList[i];
            shape.LineColor = Color.green;

            AABB aabb = AABB.AABBByPoly(shape.vertices);
            List<Vector2> poly = aabb.AABB2Points();
            LineTool.Instance.DrawPolygon(poly, Color.blue, 0.1f);
        }
        for (int i = 0; i < shapeList.Count; i++)
        {
            Shape2D shape = shapeList[i];
            List<Vector2> vs = new List<Vector2>();
            for (int j = 0; j < shape.vertices.Count; j++)
            {
                Vector2 v2 = shape.vertices[j];
                vs.Add(new Vector2(v2.x, v2.y));
            }
            if(i == selectedIndex)
            {
                aabbSelect = AABB.AABBByPoly(vs);
            }
            else
            {
                polys.Add(vs);
            }
        }

        tree = new AABBTree(polys);
        hitNodes = tree.Traverse(HitTest);
        if (hitNodes != null && hitNodes.Count > 0)
        {
            for (int i = 0; i < hitNodes.Count; i++)
            {
                AABBNode node = hitNodes[i];
                if (node.IsLeaf)
                {
                    if (node.polys != null && node.polys.Count == 1)
                    {
                        List<Vector2> poly = node.polys[0];
                        LineTool.Instance.DrawPolygon(poly, Color.red);
                    }
                }
            }
        }
    }
    private bool HitTest(AABBNode node)
    {
        if(node.IsLeaf)
        {
        }
        else
        {
            List<Vector2> poly = node.aabbNode.AABB2Points();
            LineTool.Instance.DrawPolygon(poly, Color.grey);
        }
        bool isHit = aabbSelect.IntersectsAABB(node.aabbNode);
        return isHit;
    }
}